from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from .serliazers import *

# Create your views here.


class TestAPIView(APIView):
    def get(self, request):
        return Response("Hellom World！")


# 学生相关
class StudentsAPIView(APIView):
    """
    学生的增删改查
    """
    def get(self, request):
        students = StudentsModel.objects.all()      # 获取到所有的学生
        serializer = StudentsSerializer(students, many=True)
        return Response(serializer.data)

    def post(self, request):
        # 增加学生，第一步是从request，也就是http请求中解析数据，然后验证数据，再添加数据
        serializer = StudentsSerializer(data=request.data)      # 数据校验
        if serializer.is_valid():       # 数据通过了校验
            serializer.save()           # 数据通过校验，进行保存
            return Response(serializer.data)
        else:
            return Response(serializer.errors)

    def put(self, request):
        id = request.data.get('id')     # 获取到要修改的学生的id
        student = StudentsModel.objects.filter(id=id)
        # 判断该学生是否存在
        if not student:
            return Response({'error': '该学生不存在'})
        serializer = StudentsSerializer(student, data=request.data, partial=True)     # partial=True允许部分更新
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors)
    def delete(self, request):
        id = request.data.get('id')  # 获取到要修改的学生的id
        student = StudentsModel.objects.filter(id=id)
        # 判断该学生是否存在
        if not student:
            return Response({'error': '该学生不存在'})
        student.delete()
        return Response({'success': '删除成功'})

class Sttudents2APIView(APIView):
    def get(self, request,pk):
        student = StudentsModel.objects.filter(id=pk)           # filter返回的是个数组
        if not student:
            return Response({'error': '该学生不存在'})
        serializer = StudentsSerializer(student[0])      # 获取到数组中的第一个元素
        return Response(serializer.data)